package com.lianwei.controller;

import com.google.code.kaptcha.Producer;
import com.lianwei.enums.SendCodeEnum;
import com.lianwei.enums.UserCodeEnum;
import com.lianwei.service.NotifyService;
import com.lianwei.util.CommonUtil;
import com.lianwei.util.JsonData;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/*
 *@ClassName NotifyController
 *@Description 验证码流程控制
 *@Author Kuiwen.Sun
 *@Date 2022/1/11 11:00
 *@Version 1.0
 */
@Slf4j
@RestController
@Api(tags = "验证码模块")
@RequestMapping("/notify")
public class NotifyController {

    @Autowired
    private Producer captchaProducer;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private NotifyService notifyService;
    //验证码有效期
    private static final long CAPTCHA_CODE_EXPIRED = 60 * 1000 * 10;


    @GetMapping("/captcha")
    @ApiOperation(value = "获取图形验证码",httpMethod = "GET")
    public void getCaptcha(HttpServletRequest request, HttpServletResponse response){
        //生成验证码
        String captcha = captchaProducer.createText();
        //将验证码存入redis 设置自动过期时间
        redisTemplate.opsForValue().set(getRedisKey(request),captcha,CAPTCHA_CODE_EXPIRED, TimeUnit.MILLISECONDS);
        log.info("验证码为:{}",captcha);
        BufferedImage captchaImage = captchaProducer.createImage(captcha);
        //获取响应输出流，把验证码以jpg格式响应客户端
        //try(Xxx xx = ...;) xx会自动关闭 try()的括号中可以写多行声明,每个声明的变量类型都必须是Closeable的子类,用分号隔开.
        try (ServletOutputStream outputStream = response.getOutputStream()){
            ImageIO.write(captchaImage,"jpg",outputStream);
            outputStream.flush();
        } catch (IOException e) {
            log.error("获取图形验证码异常:{}",e);
        }
    }

    @ApiOperation(value = "发送邮件验证码",httpMethod = "POST")
    @ApiImplicitParams({@ApiImplicitParam(name = "mail",dataType = "String",value = "用户邮箱",required = true)
            ,@ApiImplicitParam(name = "code",value = "之前获取的图形验证码",dataType = "String",required = true)})
    @GetMapping("send_email_code")
    public JsonData snedRegisterCode(@RequestParam("mail") String mail,@RequestParam("code")String code,HttpServletRequest request){
        String redisKey = getRedisKey(request);
        String captcha = String.valueOf(redisTemplate.opsForValue().get(redisKey));
        if (code==null||captcha==null||!code.equals(captcha)){
            redisTemplate.delete(redisKey);
            return JsonData.buildResult(UserCodeEnum.CODE_ERROR);
        }
        redisTemplate.delete(redisKey);
        return notifyService.sendEmailCode(SendCodeEnum.USER_REGISTER,mail);
    }



    public String getRedisKey(HttpServletRequest request){
        String ipAddress = CommonUtil.getIpAddr(request);
        String userAgent = request.getHeader("User-Agent");
        String redisKey="user-service:captcha:"+CommonUtil.MD5(ipAddress+userAgent);
        return redisKey;
    }



}
